package com.pethospital.service.impl;

import com.pethospital.dao.HealthRecordDao;
import com.pethospital.dao.PetDao;
import com.pethospital.dao.impl.HealthRecordDaoImpl;
import com.pethospital.dao.impl.PetDaoImpl;
import com.pethospital.entity.HealthRecord;
import com.pethospital.entity.PageResult;
import com.pethospital.entity.Pet;
import com.pethospital.service.HealthRecordService;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.List;

/**
 * 健康记录服务实现类
 * Health Record Service Implementation
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class HealthRecordServiceImpl implements HealthRecordService {
    
    private HealthRecordDao healthRecordDao = new HealthRecordDaoImpl();
    private PetDao petDao = new PetDaoImpl();
    
    @Override
    public HealthRecord getHealthRecordById(Integer recordId) {
        if (recordId == null || recordId <= 0) {
            return null;
        }
        return healthRecordDao.findById(recordId);
    }
    
    @Override
    public List<HealthRecord> getHealthRecordsByPetId(Integer petId) {
        if (petId == null || petId <= 0) {
            return null;
        }
        return healthRecordDao.findByPetId(petId);
    }
    
    @Override
    public List<HealthRecord> getHealthRecordsByOwnerId(Integer ownerId) {
        if (ownerId == null || ownerId <= 0) {
            return null;
        }
        return healthRecordDao.findByOwnerId(ownerId);
    }
    
    @Override
    public boolean addHealthRecord(HealthRecord healthRecord) {
        // 验证健康记录数据
        String validationResult = validateHealthRecord(healthRecord, false);
        if (validationResult != null) {
            return false;
        }
        
        // 验证宠物是否存在
        Pet pet = petDao.findById(healthRecord.getPetId());
        if (pet == null) {
            return false;
        }
        
        return healthRecordDao.insert(healthRecord) > 0;
    }
    
    @Override
    public boolean updateHealthRecord(HealthRecord healthRecord) {
        if (healthRecord == null || healthRecord.getRecordId() == null) {
            return false;
        }
        
        // 验证健康记录数据
        String validationResult = validateHealthRecord(healthRecord, true);
        if (validationResult != null) {
            return false;
        }
        
        // 验证宠物是否存在
        Pet pet = petDao.findById(healthRecord.getPetId());
        if (pet == null) {
            return false;
        }
        
        return healthRecordDao.update(healthRecord) > 0;
    }
    
    @Override
    public boolean deleteHealthRecord(Integer recordId) {
        if (recordId == null || recordId <= 0) {
            return false;
        }
        
        return healthRecordDao.delete(recordId) > 0;
    }
    
    @Override
    public boolean batchDeleteHealthRecords(Integer[] recordIds) {
        if (recordIds == null || recordIds.length == 0) {
            return false;
        }
        
        return healthRecordDao.batchDelete(recordIds) > 0;
    }
    
    @Override
    public List<HealthRecord> getAllHealthRecords() {
        return healthRecordDao.findAll();
    }
    
    @Override
    public PageResult<HealthRecord> getHealthRecordsByPage(int currentPage, int pageSize) {
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;
        
        return healthRecordDao.findByPage(currentPage, pageSize);
    }
    
    @Override
    public PageResult<HealthRecord> getHealthRecordsByPetIdAndPage(Integer petId, int currentPage, int pageSize) {
        if (petId == null || petId <= 0) {
            return new PageResult<>();
        }
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;
        
        return healthRecordDao.findByPetIdAndPage(petId, currentPage, pageSize);
    }
    
    @Override
    public PageResult<HealthRecord> getHealthRecordsByOwnerIdAndPage(Integer ownerId, int currentPage, int pageSize) {
        if (ownerId == null || ownerId <= 0) {
            return new PageResult<>();
        }
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;
        
        return healthRecordDao.findByOwnerIdAndPage(ownerId, currentPage, pageSize);
    }
    
    @Override
    public PageResult<HealthRecord> searchHealthRecords(String petName, String diagnosis, String doctorName,
                                                       Date visitDateStart, Date visitDateEnd, Integer ownerId,
                                                       int currentPage, int pageSize) {
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;
        
        return healthRecordDao.findByCondition(petName, diagnosis, doctorName,
                visitDateStart, visitDateEnd, ownerId, currentPage, pageSize);
    }
    
    @Override
    public long getTotalHealthRecordsCount() {
        return healthRecordDao.countAll();
    }
    
    @Override
    public long getHealthRecordsCountByPetId(Integer petId) {
        if (petId == null || petId <= 0) {
            return 0;
        }
        return healthRecordDao.countByPetId(petId);
    }
    
    @Override
    public long getHealthRecordsCountByOwnerId(Integer ownerId) {
        if (ownerId == null || ownerId <= 0) {
            return 0;
        }
        return healthRecordDao.countByOwnerId(ownerId);
    }
    
    @Override
    public List<HealthRecord> getRecordsNeedingFollowUp() {
        return healthRecordDao.findRecordsNeedingFollowUp();
    }
    
    @Override
    public List<HealthRecord> getRecentHealthRecords(Integer petId, int limit) {
        if (petId == null || petId <= 0) {
            return null;
        }
        if (limit <= 0) limit = 5;
        
        return healthRecordDao.findRecentRecords(petId, limit);
    }
    
    @Override
    public HealthRecord getLatestHealthRecordByPetId(Integer petId) {
        if (petId == null || petId <= 0) {
            return null;
        }
        return healthRecordDao.findLatestByPetId(petId);
    }
    
    @Override
    public List<HealthRecord> getTodayHealthRecords() {
        return healthRecordDao.findTodayRecords();
    }
    
    @Override
    public List<HealthRecord> getHealthRecordsByCostRange(Double minCost, Double maxCost) {
        if (minCost == null) minCost = 0.0;
        if (maxCost == null) maxCost = Double.MAX_VALUE;
        if (minCost > maxCost) {
            Double temp = minCost;
            minCost = maxCost;
            maxCost = temp;
        }
        
        return healthRecordDao.findByCostRange(minCost, maxCost);
    }
    
    @Override
    public List<Object[]> getDoctorStatistics() {
        return healthRecordDao.getDoctorStatistics();
    }
    
    @Override
    public List<Object[]> getMonthlyStatistics(int year) {
        if (year <= 0) {
            year = java.time.Year.now().getValue();
        }
        return healthRecordDao.getMonthlyStatistics(year);
    }
    
    @Override
    public boolean hasPermission(Integer recordId, Integer userId, boolean isAdmin) {
        if (recordId == null || recordId <= 0 || userId == null || userId <= 0) {
            return false;
        }
        
        // 管理员有所有权限
        if (isAdmin) {
            return true;
        }
        
        // 普通用户只能访问自己宠物的健康记录
        HealthRecord healthRecord = healthRecordDao.findById(recordId);
        if (healthRecord == null) {
            return false;
        }
        
        Pet pet = petDao.findById(healthRecord.getPetId());
        if (pet == null) {
            return false;
        }
        
        return pet.getOwnerId().equals(userId);
    }
    
    @Override
    public String validateHealthRecord(HealthRecord healthRecord, boolean isUpdate) {
        if (healthRecord == null) {
            return "健康记录不能为空";
        }
        
        // 更新操作需要记录ID
        if (isUpdate && healthRecord.getRecordId() == null) {
            return "记录ID不能为空";
        }
        
        // 验证宠物ID
        if (healthRecord.getPetId() == null || healthRecord.getPetId() <= 0) {
            return "宠物ID不能为空";
        }
        
        // 验证就诊日期
        if (healthRecord.getVisitDate() == null) {
            return "就诊日期不能为空";
        }
        
        // 验证症状
        if (healthRecord.getSymptoms() == null || healthRecord.getSymptoms().trim().isEmpty()) {
            return "症状描述不能为空";
        }
        if (healthRecord.getSymptoms().length() > 1000) {
            return "症状描述不能超过1000个字符";
        }
        
        // 验证诊断结果
        if (healthRecord.getDiagnosis() == null || healthRecord.getDiagnosis().trim().isEmpty()) {
            return "诊断结果不能为空";
        }
        if (healthRecord.getDiagnosis().length() > 1000) {
            return "诊断结果不能超过1000个字符";
        }
        
        // 验证治疗方案
        if (healthRecord.getTreatment() != null && healthRecord.getTreatment().length() > 1000) {
            return "治疗方案不能超过1000个字符";
        }
        
        // 验证用药记录
        if (healthRecord.getMedication() != null && healthRecord.getMedication().length() > 1000) {
            return "用药记录不能超过1000个字符";
        }
        
        // 验证医生姓名
        if (healthRecord.getDoctorName() != null && healthRecord.getDoctorName().length() > 50) {
            return "医生姓名不能超过50个字符";
        }
        
        // 验证费用
        if (healthRecord.getCost() != null && healthRecord.getCost().compareTo(BigDecimal.ZERO) < 0) {
            return "费用不能为负数";
        }
        if (healthRecord.getCost() != null && healthRecord.getCost().compareTo(new BigDecimal("999999.99")) > 0) {
            return "费用不能超过999999.99";
        }
        
        // 验证备注
        if (healthRecord.getNotes() != null && healthRecord.getNotes().length() > 2000) {
            return "备注不能超过2000个字符";
        }
        
        // 验证复诊日期
        if (healthRecord.getNextVisitDate() != null && 
            healthRecord.getNextVisitDate().before(healthRecord.getVisitDate())) {
            return "复诊日期不能早于就诊日期";
        }
        
        return null; // 验证通过
    }
}
